﻿using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WP8_PPS.Helpers
{
    /// <summary>
    /// An Abstraction to use the INotifyPropertyChanged interface to implement data binding notifications
    /// </summary>
    public abstract class BindableBase : INotifyPropertyChanged
    {
        /// <summary>
        /// Property to call when data has been changed
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Function to set property and call the event to trigger the UI
        /// </summary>
        /// <typeparam name="T">Using generics so that the class knows whom called it</typeparam>
        /// <param name="storage">A reference to the storage property</param>
        /// <param name="value">Value to store in the property</param>
        /// <param name="propertyName">Name of the property to notify</param>
        /// <returns>True if all works</returns>
        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
        {
            if (object.Equals(storage, value)) return false;
            storage = value;
            this.OnPropertyChanged(propertyName);
            return true;
        }

        /// <summary>
        /// Function to call changed property event
        /// </summary>
        /// <param name="propertyName">Name of the property to notify</param>
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var eventHandler = this.PropertyChanged;
            if (eventHandler != null)
            {
                App.RootFrame.Dispatcher.BeginInvoke(() =>
                    {
                        eventHandler(this, new PropertyChangedEventArgs(propertyName));
                    });
            }
        }
    }
}
